package edu.put.sk.nrpp;

import java.util.ArrayList;

import edu.put.sk.nrpp.ui.Router;
import edu.put.sk.nrpp.ui.RouterList;

public class Floyd {
	private RouterList _routerList;
	private int floydTable[][];	
	private ArrayList<Router> neighbors = new ArrayList<Router>();
	public Floyd(RouterList rList){
		this._routerList=rList;
	}
	
	public void run(ArrayList<Router> routers){
		this.floydTable=new int[routers.size()][routers.size()];
		for (int i=0;i<routers.size();i++){
			this.neighbors=routers.get(i).allNeighbors();
			this.floydTable[i][i]=0;
			for (int j=i+1;j<routers.size();j++){
				for (Object o:this.neighbors){
					if (o.equals(routers.get(j))){
						this.floydTable[i][j]=1;
						this.floydTable[j][i]=1;
						break;
					}
					else{
						this.floydTable[i][j]=java.lang.Integer.MAX_VALUE;
						this.floydTable[j][i]=java.lang.Integer.MAX_VALUE;
					}
				}
			}
		}
		this.startAlgorihm(routers.size());
		this.show(routers);
		int sum=0;
		for (int i=0;i<routers.size();i++){
			for (int j=0; j<routers.size();j++){
				sum+=this.floydTable[i][j];
			}
			this._routerList.addDistance(routers.get(i).id, sum);
			sum=0;
		}
	}
	
	private void startAlgorihm(int tableSize){
		for (int i=0;i<tableSize;i++){
			algorithmIteration(i,tableSize);
		}
	}
	
	private void algorithmIteration(int iteration, int tableSize){
		for (int i=0;i<tableSize;i++){
			for (int j=0;j<tableSize;j++){
				if ((i!=iteration)&&(j!=iteration)){
					if ((this.floydTable[i][iteration]!=java.lang.Integer.MAX_VALUE)&&
							(this.floydTable[iteration][j]!=java.lang.Integer.MAX_VALUE)){
						this.floydTable[i][j]=min(this.floydTable[i][j],this.floydTable[iteration][j]+
								this.floydTable[i][iteration]);
					}
				}
			}
		}
	}
	
	private int min(int a, int b){
		if (a<b){
			return a;
		}
		return b;
	}
	
	private void show(ArrayList<Router> routers){
		for (int i=0;i<routers.size();i++){
			System.out.println(routers.get(i).id);
		}
		for (int i=0;i<routers.size();i++){
			for (int j=0;j<routers.size();j++){
				System.out.print(this.floydTable[i][j]);
			}
			System.out.println();
		}
	}
}
